<?php
/**
 * wechat端， v3.0版的推荐商品
 * Author: lyun
 * Date: 2019/4/3
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\ApiController;
use App\Http\Controllers\Service\Wechat\RecommendProductV3Service;
use App\Http\Middleware\WechatAuth;
use App\Http\Requests\Wechat\RecommendProductV3IndexRequest;
use App\Models\OpenWechat\WechatUser;
use App\Models\Store\SkinRecord;
use App\Models\Store\Store;

class RecommendProductV3Controller extends ApiController
{
    const ROUTES = [
        'index' => 'wechat.recommend.product.v3.index'
    ];

    /**
     * 允许客户后台自定义修改测肤结果的分数与推荐产品的关联关系
     * @test
     * @param RecommendProductV3IndexRequest $request
     * @param RecommendProductV3Service $recommend_product_service
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(RecommendProductV3IndexRequest $request, RecommendProductV3Service $recommend_product_service)
    {
        $skin_record_id = (int)$request->skin_record_id;
        $skin_detector_id = (int)$request->skin_detector_id;
        $type_skin_record_id = (int)$request->type_skin_record_id;
        $openid = $request->openid;
        $sex = $request->sex;

        // 检测肤质检测数据
        /** @var SkinRecord $skin_record */
        $skin_record = (new SkinRecord)->find($skin_record_id);
        $sub_skin_record = $skin_record->getWaxOrHmSkinRecordById($type_skin_record_id);
            $this->checkItemExist($skin_record, trans('wechat.skin_record'));
            $this->checkIsTrue($skin_record->skin_detector_id === $skin_detector_id, trans('wechat.skin_detector'));
            $this->checkIsTrue($skin_record->wechatUser->openid === $openid, trans('wechat.skin_record_wechat_user_not_match'));
            $this->checkIsTrue($sub_skin_record, trans('wechat.skin_record_error'));

        // 获取customer_id和store_id
        $store_id = $skin_record->store_id;
        $store = (new Store)->find($store_id);
        $customer_id = $store->customer_id;

        // 获取wax/hm/cam检测项的阶段分数对应的商品信息。
        $recommend_products = $recommend_product_service->getRecommendProducts($sub_skin_record, $skin_detector_id, $customer_id, $sex, $store_id);

        // 根据category_id分组商品
        $group_recommend_products = $recommend_product_service->transformRecommendProducts($recommend_products);

        return $this->response(compact('group_recommend_products'));

    }
}
